package com.zenghus.v2.mapper;

import com.zenghus.v2.annotation.Select;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;


public class MapperRegistory {

    public static final Map<String,MapperDate> mothodsqlMapper=new HashMap();

    /**
     * registerMapper
     * @param mapperPath
     * @throws Exception
     */
    public void build(String mapperPath) throws Exception{
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = mapperPath.replace(".", "/");
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }
        for (File directory : dirs) {
            File[] files = directory.listFiles();
            for (File file : files) {
                String classname=mapperPath + "." + file.getName().substring(0, file.getName().length() - 6);
                Class clazz=(Class) Class.forName(classname);
                if(clazz.isInterface()){
                    Method[] methods=clazz.getMethods();
                    for (int i = 0; i <methods.length ; i++) {
                        Method method=methods[i];
                        Select select=method.getAnnotation(Select.class);
                        if(select !=null){
                            mothodsqlMapper.put(classname+"."+method.getName(),new MapperDate(select.sql(),method.getReturnType()));
                        }
                    }
                }
            }
        }
    }

    public class MapperDate<T>{
        private String sql;
        private Class<T> type;

        MapperDate(String sql,Class<T> type){
            this.sql=sql;
            this.type=type;
        }

        public String getSql() {
            return sql;
        }

        public void setSql(String sql) {
            this.sql = sql;
        }

        public Class<T> getType() {
            return type;
        }

        public void setType(Class<T> type) {
            this.type = type;
        }
    }

}
